﻿using System;
using System.Web.Mvc;

namespace IGMVC.Web.Models
{
    public class IssueRichBinderAttribute : CustomModelBinderAttribute
    {
        public override IModelBinder GetBinder()
        {
            return new IssueRichBinder();
        }
    }

    public class IssueRichBinder : IModelBinder
    {
        public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            Issue issue = new Issue();
            var form = controllerContext.RequestContext.HttpContext.Request.Form;

            string desc = "", issueTypeId = "0", severity = "0";
            foreach (string key in form.Keys)
            {
                if (key.Contains("Description"))
                {
                    desc = form[key];
                }
                else if (key.Contains("Severity:i"))
                {
                    severity = form[key];
                }
            }

            int num;
            issueTypeId = form["IssueTypeId"];
            if(int.TryParse(issueTypeId,out num))
            {
                issue.IssueTypeId = num;
            }

            issue.Description = desc;
            issue.Severity = this.GetSliderValue(severity);
            issue.Title = form["Title"];
            return issue;
        }

        private int GetSliderValue(string value)
        {
            value = value.Substring(0, value.IndexOf('|'));
            return Convert.ToInt32(Math.Round(double.Parse(value),0));
        }
    }
}